from typing import List, Optional, Dict, Any
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from sqlalchemy.orm import selectinload

from app.models.models import School
from app.schemas.schemas import SchoolCreate


async def get_schools(db: AsyncSession) -> List[School]:
    """获取所有学校"""
    result = await db.execute(select(School).order_by(School.id))
    return result.scalars().all()


async def get_school(db: AsyncSession, school_id: int) -> Optional[School]:
    """根据ID获取学校"""
    result = await db.execute(select(School).filter(School.id == school_id))
    return result.scalars().first()


async def create_school(db: AsyncSession, school: SchoolCreate) -> School:
    """创建学校"""
    db_school = School(**school.model_dump())
    db.add(db_school)
    await db.commit()
    await db.refresh(db_school)
    return db_school


async def update_school(db: AsyncSession, school_id: int, school_data: Dict[str, Any]) -> Optional[School]:
    """更新学校信息"""
    db_school = await get_school(db, school_id)
    if db_school:
        for key, value in school_data.items():
            setattr(db_school, key, value)
        await db.commit()
        await db.refresh(db_school)
    return db_school
